import json
import re
import os
class Vis_seq_in_danger_func:
    def __init__(self,danger_seq_path,model_dec_seq):
        self.danger_seq_path=danger_seq_path
        self.model_dec_seq=model_dec_seq
    def find_seq(self):
        match = re.search(r'@([^@]+)@([^@]+)@([^@]+)@([^@]+)(?=@.*\.json)', self.model_dec_seq)
        if match:
    # 输出最后一个 @ 和 .json 之间的内容
            file_name = match.group(4)
        with open(danger_seq_path, 'r') as json_file:
            result = []
            temp = []
            all_data = json.load(json_file)
            for idx,dang_date_info in enumerate(all_data):
                if dang_date_info['file'].rstrip('.out') == file_name:
                    dang_data=dang_date_info
                    break
            for item in dang_data['instructions']:
                if 'idx' in item:
                    if temp:
                        result.append(temp)
                    temp = [item]
                else:
                    temp.append(item)
            if temp:
                result.append(temp)
            fragment_indices={}
            fragment_indices['file'] = dang_data['file']
            with open(self.model_dec_seq, 'r') as json_file_2:
                new_dict = {i: [] for i in range(len(result))}
                for idx, entry in enumerate(json.load(json_file_2)["0"]):
                    func_addr = entry["func_addr"]
                    func_addr_value = int(func_addr, 16)

                    for i, segment in enumerate(result):
                        for seg_entry in segment:
                            if 'addr' in seg_entry and seg_entry['addr'] == func_addr_value:
                                new_dict[i].append(idx)

                fragment_indices.update(new_dict)
        fragment_indices['dangerous_functions']=dang_data['dangerous_functions']
        output_file_name = os.path.join(file_name + '.json')
        with open(output_file_name, "w") as json_file:
            json.dump(fragment_indices, json_file)
        print(fragment_indices)
if __name__ == '__main__':
    danger_seq_path = '/home/wang1/zz_static_project/my_task/s02.json'
    model_dec_seq = '/home/wang1/zz_static_project/s01/model_dec_seq/preprocessed_data@CWE121_Stack_Based_Buffer_Overflow_O0_filtered_newest20241110@s02@bad@CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_ncpy_05@cfg_graph.json'
    seq_find=Vis_seq_in_danger_func(danger_seq_path,model_dec_seq)
    seq_find.find_seq()
